package chaoyue.study.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * 配置自定义负载均衡策略
 * 这边切换为随机策略
 */
@Slf4j
@LoadBalancerClients(defaultConfiguration = LoadBalanceConfig.class)
@Configuration
public class LoadBalanceConfig {
    @Bean
    public ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment e, LoadBalancerClientFactory factory) {
        // 获取负载均衡客户端名称，即provider的名称
        String name = e.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        log.info("负责均衡 获取服务名称 -> {}", name);
        // 从所有provider实例中指定名称的实例列表中随机选择一个实例
        return new RandomLoadBalancer(factory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
    }
}
